<?php

namespace App\Http\Controllers\Api;

use App\Models\TcmBook;
use App\Models\TcmBookChapters;
use App\Models\TcmBookCollect;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class TcmBookController extends Controller
{
    public function collectList(Request $request)
    {
        $memberId = auth('api')->user()->id;

        $list = TcmBookCollect::with(['book' => function ($q) {
            return $q->select(['id', 'name', 'img', 'sound'])->where('status', 1);
        }])->whereHas('book')->where('member_id', $memberId)->get();

        return $this->_success(['list' => $list]);
    }

    public function collect(int $id)
    {
        $memberId = auth('api')->user()->id;

        if (!TcmBook::where('status', 1)->find($id)) return $this->error('书籍不存在');

        $record = TcmBookCollect::where([
            'member_id' => $memberId,
            'book_id'   => $id
        ])->first();

        if ($record) {
            $record->delete();

            return $this->_success(['collect' => null]);
        }

        TcmBookCollect::create([
            'member_id' => $memberId,
            'book_id'   => $id
        ]);

        return $this->_success(['collect' => [
            'book_id'                 => $id,
            'member_id'               => $memberId,
            'history_book_chapter_id' => 0,
        ]]);
    }

    public function batchUnCollect(Request $request)
    {
        $ids = $request->input('ids');
        $ids = array_filter(explode(',', $ids));

        if (!$ids) return $this->error('请选择书籍');

        TcmBookCollect::where('member_id', auth('api')->user()->id)
            ->whereIn('id', $ids)
            ->delete();

        return $this->success('操作成功');
    }

    public function bookList(Request $request)
    {
        $list = TcmBook::select(['id', 'author', 'dynasty', 'name', 'img', 'sound'])
            ->where('status', 1)
            ->orderByDesc('sort')
            ->orderByDesc('id')
            ->paginate();

        $memberId = auth('api')->user()->id;
        $collectRecord = TcmBookCollect::where('member_id', $memberId)->get();

        foreach ($list as $item) {
            $item->collect = $collectRecord->where('book_id', $item->id)->first();
        }

        return $this->_success(['list' => $list->items()]);
    }

    public function bookDetails(Request $request)
    {
        $bookId = $request->input('book_id', 0);
        if (!$bookId) return $this->error('书籍ID不能为空');

        $book = TcmBook::where('status', 1)->find($bookId);
        if (!$book) return $this->error('书不存在');

        $list = Cache::remember('BOOK_CHAPTER_' . $bookId, 60 * 30, function () use ($bookId) {
            return TcmBookChapters::select(['id', 'book_id', 'name', 'playable', 'subhead', 'volume'])
                ->where('book_id', $bookId)
                ->orderBy('sort')
                ->orderByDesc('id')
                ->get();
        });

        $memberId = auth('api')->user()->id;
        $collect = TcmBookCollect::where('book_id', $bookId)->where('member_id', $memberId)->first();

        return $this->_success(['info' => $book, 'chapters' => $list, 'collect' => $collect]);
    }

    public function bookChapterDetails(Request $request)
    {
        $bookId = $request->input('book_id', 0);
        if (!$bookId) return $this->error('书籍ID不能为空');

        $book = TcmBook::where('status', 1)->find($bookId);
        if (!$book) return $this->error('书不存在');

        $chapterId = $request->input('chapter_id', 0);
        $chapter = TcmBookChapters::where('book_id', $bookId)->find($chapterId);
        if (!$chapter) return $this->error('章节不存在');

        $list = Cache::remember('BOOK_CHAPTER_' . $bookId, 60 * 30, function () use ($bookId) {
            return TcmBookChapters::select(['id', 'book_id', 'name', 'playable', 'subhead', 'volume'])
                ->where('book_id', $bookId)
                ->orderBy('sort')
                ->orderByDesc('id')
                ->get();
        });

        $arr = $list->pluck('id')->all();
        $index = array_search($chapterId, $arr);

        if ($index !== false) {
            $nextId = $arr[$index + 1] ?? null;
        }

        TcmBookCollect::where([
            'book_id'   => $bookId,
            'member_id' => auth('api')->user()->id,
        ])->update(['history_book_chapter_id' => $chapterId]);

        return $this->_success(['info' => $chapter, 'next_id' => $nextId ?? null]);
    }

    public function search(Request $request)
    {
        $keyword = $request->input('keyword');
        if (!$keyword) return $this->error('关键词不能为空');

        $books = TcmBook::where('name', 'like', '%' . $keyword . '%')->where('status', 1)->get();

        $memberId = auth('api')->user()->id;
        $collectRecord = TcmBookCollect::where('member_id', $memberId)->get();

        foreach ($books as $book) {
            $book->collect = $collectRecord->where('book_id', $book->id)->first();
        }

        $keywordArr = explode('|', cutKeyword($keyword));
        array_shift($keywordArr);

        $chapters = TcmBookChapters::with(['book' => function ($q) {
            return $q->select(['id', 'name']);
        }])->select(['id', 'book_id', 'name', 'subhead', 'describe'])->whereHas('book', function ($q) {
            return $q->where('status', 1);
        })->where(function ($q) use ($keyword, $keywordArr) {
            $q->where('name', 'like', $keyword . '%')->orWhere(function ($q) use ($keywordArr) {
                foreach ($keywordArr as $key => $word) {
                    $key == 0 ?
                        $q->where('describe', 'like', $word . '%') :
                        $q->orWhere('describe', 'like', $word . '%');
                }
            });
        })->orderBy('sort')->orderByDesc('id')->paginate();

        return $this->_success([
            'books'    => $books,
            'chapters' => $chapters->items(),
        ]);
    }

    public function chaptersSearch(Request $request)
    {
        $bookId = $request->input('book_id');
        if (!$bookId) return $this->error('书籍ID不能为空');

        $book = TcmBook::where('status', 1)->find($bookId);
        if (!$book) return $this->error('书籍不存在');

        $keyword = $request->input('keyword');
        if (!$keyword) return $this->error('关键词不能为空');

        $keywordArr = explode('|', cutKeyword($keyword));
        array_shift($keywordArr);

        $chapters = TcmBookChapters::with(['book' => function ($q) {
            return $q->select(['id', 'name']);
        }])->select(['id', 'book_id', 'name', 'subhead', 'describe'])
            ->where('book_id', $bookId)
            ->where(function ($q) use ($keyword, $keywordArr) {
                $q->where('name', 'like', $keyword . '%')->orWhere(function ($q) use ($keywordArr) {
                    foreach ($keywordArr as $key => $word) {
                        $key == 0 ?
                            $q->where('describe', 'like', $word . '%') :
                            $q->orWhere('describe', 'like', $word . '%');
                    }
                });
            })
            ->orderBy('sort')->orderByDesc('id')->paginate();

        return $this->_success([
            'chapters' => $chapters->items(),
        ]);
    }
}
